package com.cn.tianxin.ssserver.service;

import com.cn.tianxin.ssserver.constants.WeixinConstans;
import com.cn.tianxin.ssserver.ext.WXAccessToken;
import com.cn.tianxin.ssserver.utils.QRCodeUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class WeixinService {

    @Autowired
    RestTemplate restTemplate;

    /**
     * http请求，返回token access_token的有效期目前为2个小时
     * 请求后，如果返回错误，或超时，都重新获取
     * @return
     */
    public String getWXAccessToken(){
        return WXAccessToken.getToken().getAccess_token();
    }

    /**
     * 根据当前配置，生成用户网页授权 字符串
     * @param state    标识哪一次用户扫码。用来后续确定系统用户与回调时的openid关系
     * @return
     */
    private static String generateAuthURLString(String state){
        return generateAuthURLString(state,"snsapi_userinfo");    //默认获取用户信息    需要用户关注公众号
    }

    public static String generateAuthURLString(String state,String scope){
        try {
            StringBuilder urlStrSb = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
            urlStrSb.append("appid="+ URLEncoder.encode(WeixinConstans.appid,WeixinConstans.defaultEncode)+"&");

            if (scope!=null && "snsapi_userinfo".equals(scope)){
                //urlStrSb.append("redirect_uri="+ URLEncoder.encode(WebappConstans.host+"/weixinTest/authCallBack",WeixinConstans.defaultEncode)+"&");
                urlStrSb.append("redirect_uri="+ URLEncoder.encode(WeixinConstans.authRedirectUrl,WeixinConstans.defaultEncode)+"&");
                urlStrSb.append("response_type="+ URLEncoder.encode("code",WeixinConstans.defaultEncode)+"&");
                urlStrSb.append("scope="+ URLEncoder.encode("snsapi_userinfo",WeixinConstans.defaultEncode)+"&");
            }else {
                //urlStrSb.append("redirect_uri="+ URLEncoder.encode(WebappConstans.host+"/weixinTest/authCallBack",WeixinConstans.defaultEncode)+"&");
                urlStrSb.append("redirect_uri="+ URLEncoder.encode(WeixinConstans.authRedirectUrl,WeixinConstans.defaultEncode)+"&");
                urlStrSb.append("response_type="+ URLEncoder.encode("code",WeixinConstans.defaultEncode)+"&");
                urlStrSb.append("scope="+ URLEncoder.encode("snsapi_base",WeixinConstans.defaultEncode)+"&");
            }
            urlStrSb.append("state="+ URLEncoder.encode(state,WeixinConstans.defaultEncode));
            urlStrSb.append("#wechat_redirect");

            return urlStrSb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    //生成一次用户 扫码网页授权id
    public static String generateRelId(){
        long l = System.currentTimeMillis();
        Random random = new Random();
        int i = random.nextInt(100);
        String randNoStr = "00" + i;
        randNoStr = randNoStr.substring(randNoStr.length()-2);
        return l+"A"+randNoStr;
    }

    public BufferedImage getAuthImage(String empId){
        //生成relId
        String relId = generateRelId();

        //后台保存empId与relId关系
        // 记录本地系统用户信息，与relId关联
        //todo
        System.out.println("emp("+empId+") relate relId("+relId+")");

        //生成 网页授权二维码
        String urlStr = generateAuthURLString(relId,null);
        System.out.println("WeixinService.getAuthImage=>urlStr    "+urlStr);

        try {
            return QRCodeUtil.createImgWithLogo(urlStr,WeixinService.class.getClassLoader().getResource("/static/img/saisai_logo.png").getPath(),true);
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }

    }

    //网页授权 使用指定appid和secret 和前台返回的code 从微信获取 access_token和用户openId
    public Map<String,Object> codeToAuthToken(String code,String appid,String secret) throws IOException {
        //由第一步获取的code，请求 网页授权access_token
        String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+
                //WeixinConstans.appid+"&secret="+WeixinConstans.secret+"&code="+code+"&grant_type=authorization_code";
                appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        int available = inputStream.available();
        byte[] bytes = new byte[available];

        int read = inputStream.read(bytes);
        if (inputStream!=null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String responsStr = new String(bytes, WeixinConstans.defaultEncode);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(responsStr);
        if (responsStr!=null){
            Map<String,Object> resultMap = new HashMap<>();
            resultMap = mapper.readValue(responsStr, Map.class);
            return resultMap;
        }

        return null;
    }

    //由授权code，获取用户openid
    public Map<String,Object> getUserOpenId(String code) throws IOException {
        return codeToAuthToken(code,WeixinConstans.appid,WeixinConstans.secret);
    }

    // https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
    // 接上一步
    public Map<String,Object> getWXUserInfo(Map<String,Object> map){
        if(map==null || map.get("access_token")==null || map.get("openid")==null){
            return null;
        }

        String urlStr = "https://api.weixin.qq.com/sns/userinfo?access_token="+
                map.get("access_token")+"&openid="+map.get("openid")+"&lang=zh_CN";

        try {
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            int available = inputStream.available();
            byte[] bytes = new byte[available];

            int read = inputStream.read(bytes);
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String responseStr = new String(bytes, WeixinConstans.defaultEncode);
            ObjectMapper objectMapper = new ObjectMapper();
            Map resultMap = objectMapper.readValue(responseStr, Map.class);

            System.out.println("WeixinService.getWXUserInfo=>"+resultMap);

            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /*public static void main(String[] args) throws IOException {

        WeixinService weixinService = new WeixinService();
        Map<String, Object> map = weixinService.codeToAuthToken("0232i5e00dQ2YG1pLgf005w8e002i5eM", "wx9acea8920d122d70", "547f91b540c06dc80d2bb1afd17095e3");
        System.out.println(map);

    }*/

    public static void main(String[] args) throws WriterException, IOException {
        String urlStr = "https://www.waterman.vip/weixinTest/codeToWXXCX?redPackId=000005";
        //String urlStr = "https://www.saisaisys.com/.well-known/pki-validation/?redPackId=000008";
        BufferedImage img = QRCodeUtil.createImgWithLogo(urlStr, null, false);
        boolean png = ImageIO.write(img, "png", new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\wxxcx3.png")));
    }

    /*public static void main(String[] args) throws IOException {
        WeixinService weixinService = new WeixinService();
        BufferedImage image = weixinService.getAuthImage("tianxin");
        if (image!=null){
            File file = new File("C:\\Users\\Administrator\\Desktop\\QRimg_noUserInfo.png");
            ImageIO.write(image,"png",file);
        }
    }*/

    /*public static void main(String[] args) throws Exception {
        *//*long l = System.currentTimeMillis();
        Random random = new Random();
        int i = random.nextInt(100);*//*

        String id = generateRelId();
        String s = generateAuthURLString(id);
        System.out.println("id length=>"+id.length()+" s=>"+s);

        BufferedImage imgWithLogo = QRCodeUtil.createImgWithLogo(s, "D:\\txWorkspace\\dyvms_java\\java\\api_sdk\\ss-server\\src\\main\\resources\\static\\img\\saisai_logo.png", true);
        //System.out.println(imgWithLogo);
        File file = new File("C:\\Users\\Administrator\\Desktop\\QRimg.png");
        ImageIO.write(imgWithLogo,"png",file);
        System.out.println("done");

    }*/



}
